package com.aabte.hystrixlearn.hystrix.command;

import com.netflix.hystrix.*;

/**
 * @author Daniel
 */
public class GetCityNameCommand extends HystrixCommand<String> {

    public static final HystrixCommandKey KEY = HystrixCommandKey.Factory.asKey("GetCityNameCommand");

    private final String code;

    protected GetCityNameCommand(String code) {
        // super(Setter.withGroupKey(
        //         HystrixCommandGroupKey.Factory.asKey("GetCityNameCommandGroup"))
        //         .andCommandKey(HystrixCommandKey.Factory.asKey("GetCityNameCommand"))
        //         // 使用单独线程池
        //         .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(""))
        //         .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
        //                 // 指定线程池线程数量
        //                 .withCoreSize(10)
        //                 // 指定线程池队列达到指定阈值后，拒绝走降纸
        //                 .withQueueSizeRejectionThreshold(10))
        //         .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
        //                 .withExecutionIsolationStrategy(
        //                         HystrixCommandProperties.ExecutionIsolationStrategy.THREAD))
        // );

        super(Setter.withGroupKey(
                HystrixCommandGroupKey.Factory.asKey("GetCityNameCommandGroup"))
                .andCommandKey(KEY)
                // 使用单独信号量
                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("GetCityNameThreadPool"))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                        .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
                        .withExecutionIsolationSemaphoreMaxConcurrentRequests(15))
        );
        this.code = code;
    }

    @Override
    protected String run() throws Exception {
        // 模拟复杂的计算操作
        Thread.sleep(2000);

        switch (code) {
            case "1":
                return "beijing";
            case "2":
                return "nanjing";
            case "3":
                return "tianjin";
        }
        return "hunan";
    }
}
